<?php
namespace app\manage\controller;

use \think\Loader;
use app\manage\controller\Conn;
use app\manage\model\Order as Ordermodel;
use think\Db;
use app\manage\model\User as Usermodel;

class Order extends Conn
{
    //这里用前置操作，表示提前运行，本来要用于栏目删除子栏目呢，现在不用了
    protected $beforeActionList = [
        
    ];
    public function index()
    {
        $order=new Ordermodel(); 
      	if(request()->isPost()) {
            $data=input('post.');
            
            $start=strtotime($data['start']);
            $end=strtotime($data['end']);
            if (isset($data['start']) or isset($data['end'])) {
                $map=[];
                if ($data['start'] != '') {
                    $map[]=	['o.create_time','>',strtotime($data['start'])];
                }
                if ($data['end'] != '') {
                    $map[]=	['o.create_time','<',strtotime($data['end'])+60*60*24];
                }
            } else {
                $map=true;
            }
            
            if ($data['type']=='so') {
                $order=$order
                ->alias('o')
                ->join('user m', "o.user_id = m.id", 'LEFT')
                ->join('goods g', "o.goods_id = g.id", 'LEFT')
                ->field('o.*,m.name,m.phone,m.nickName as username,m.phone as mphone,g.goods_name')
                ->where($map)
               // ->where('g.lei', 1)
                ->where(function ($query) use ($data) {
                    if ($data['key']) {
                        $query->whereOr('m.phone', 'like', '%'.$data['key'].'%')
                            ->whereOr('m.nickName', 'like', '%'.$data['key'].'%')
                            ->whereOr('out_trade_no', 'like', '%'.$data['key'].'%')
                            ->whereOr('m.name', 'like', '%'.$data['key'].'%');
                    }
                })
                ->order('create_time desc,id desc')->paginate(12);
                // $w=Db::name('order')
                // ->alias('o')
                // ->join('user m',"o.user_id = m.id",'LEFT')
                // ->join('goods g',"o.goods_id = g.id",'LEFT')
                // ->field('o.*,m.name,m.nickName as username,m.phone as mphone,g.goods_name')
                // ->where($map)
                // ->where('o.delete_time','null')
                // ->where('g.lei',1)
                // ->where(function ($query) use($data) {
                // 	if($data['key']){
                //     $query->whereOr('m.phone', 'like','%'.$data['key'].'%')
                //         ->whereOr('m.nickName', 'like', '%'.$data['key'].'%')
                // 		->whereOr('out_trade_no', 'like', '%'.$data['key'].'%')
                // 		->whereOr('m.name', 'like', '%'.$data['key'].'%');
                // 	}
                
                // })->sum('o.goods_price_zong');
                
                // $this->assign('zong', $w);
                
            //	dump(Db::getLastSql());
            }
        } else {
            $order=$order
            ->alias('o')
            ->join('user m', "o.user_id = m.id", 'LEFT')
            ->join('goods g', "o.goods_id = g.id", 'LEFT')
            ->field('o.*,m.name,m.name as username,m.phone as mphone,g.goods_name')
           // ->where('g.lei', 1)
            ->order('create_time desc,id desc')->paginate(12);
            
            //$this->assign('zong', Db::name('order')->where('delete_time','null')->where('lei',1)->where('pay_status',1)->sum('goods_price_zong'));
            //dump(Db::getLastSql());
        }
        
        $this->assign('start', $data['start'] ?? '');
        $this->assign('end', $data['end'] ?? '');
        $this->assign('key', $data['key'] ?? '');
        
        $this->assign('order', $order);
        $this->assign('count1', $order->total());
        
        
        return $this->fetch();
    }
    public function xiaofei()
    {
        $order=new Ordermodel();
        if (request()->isPost()) {
            $data=input('post.');
            $start=strtotime($data['start']);
            $end=strtotime($data['end']);
            if (isset($data['start']) or isset($data['end'])) {
                $map=[];
                if ($data['start'] != '') {
                    $map[]=	['o.create_time','>',strtotime($data['start'])];
                }
                if ($data['end'] != '') {
                    $map[]=	['o.create_time','<',strtotime($data['end'])+60*60*24];
                }
            } else {
                $map=true;
            }
            
            
            if ($data['type']=='so') {
                $order=$order
                ->alias('o')
                ->join('user m', "o.user_id = m.id", 'LEFT')
                ->join('goods g', "o.goods_id = g.id", 'LEFT')
                ->field('o.*,m.name,m.phone,m.nickName as username,m.phone as mphone,g.goods_name')
                ->where($map)
                
                ->where('g.lei', 2)
                ->where(function ($query) use ($data) {
                    $query->whereOr('m.phone', 'like', '%'.$data['key'].'%')
                        ->whereOr('m.nickName', 'like', '%'.$data['key'].'%')
                        ->whereOr('out_trade_no', 'like', '%'.$data['key'].'%')
                        ->whereOr('m.name', 'like', '%'.$data['key'].'%');
                })
                ->order('create_time desc,id desc')->paginate(12)->each(function ($item, $key) {
                    $item->alg = $item->alg ? $item->alg : Db::name('alg')->where('type', 8)->where('order_id', $item->id)->where('uid', $item->user_id)->value('num');
                });
                
                //	dump(Db::getLastSql());
            
            // $w=Db::name('order')
            // ->alias('o')
            // ->join('user m',"o.user_id = m.id",'LEFT')
            // ->join('goods g',"o.goods_id = g.id",'LEFT')
            // ->field('o.*,m.name,m.nickName as username,m.phone as mphone,g.goods_name')
            // ->where($map)
            // ->where('o.delete_time','null')
            // ->where('g.lei',2)
            // ->where(function ($query) use($data) {
            // 	if($data['key']){
            //     $query->whereOr('m.phone', 'like','%'.$data['key'].'%')
            //         ->whereOr('m.nickName', 'like', '%'.$data['key'].'%')
            // 		->whereOr('out_trade_no', 'like', '%'.$data['key'].'%')
            // 		->whereOr('m.name', 'like', '%'.$data['key'].'%');
            // 	}
            
            // })->sum('o.goods_price_zong');
            
            // $this->assign('zong', $w);
            }
        } else {
            $order=$order
            ->alias('o')
            ->join('user m', "o.user_id = m.id", 'LEFT')
            ->join('goods g', "o.goods_id = g.id", 'LEFT')
            ->field('o.*,m.name,m.name as username,m.phone as mphone,g.goods_name')
            ->where('g.lei', 2)
            ->order('create_time desc,id desc')->paginate(12)->each(function ($item, $key) {
                //if(!(float)$item->alg){
                $item->alg = Db::name('alg')->where('type', 8)->where('order_id', $item->id)->where('uid', $item->user_id)->value('num');
                //}
            });
            //$this->assign('zong', Db::name('order')->where('lei',2)->where('delete_time','null')->where('pay_status',1)->sum('goods_price_zong'));
        }
        
    
        
        $this->assign('key', $data['key'] ?? '');
        
        $this->assign('order', $order);
        $this->assign('count1', $order->total());
        
        return $this->fetch('index');
    }
    public function ajax()
    {
        $data=input('param.');
        $order=new Ordermodel();
        if ($data['type']=='order_del') {
            $id=$data['id'];
            $info=$order->destroy($id);
            if ($info) {
                return 1;//修改成功返回1
            } else {
                return 0;
            }
        }
        if ($data['type']=='order_tui') {
            $id=$data['id'];
            $order=Db::name('order')->find($id);
            if ($order["pay_status"]==0) {
                return json(['code'=>0,'message'=>'支付后才可以退还！']);
            }
            if ($order["is_tui"]==1) {
                return json(['code'=>0,'message'=>'已经退还不能重复！']);
            }
            if ($order["lei"]==1) {
                return json(['code'=>0,'message'=>'目前只允许退还，消费商城！']);
            }
            if ($order["payment"]!=3) {
                return json(['code'=>0,'message'=>'目前只允许退还，alg支付的！']);
            }
            $alg=Db::name('alg')->where('order_id', $order['id'])->where('type', 8)->where('uid', $order['user_id'])->find();
            Db::name('alg')->insert([
                'time'=>time(),
                'type'=>11,
                'num'=>$alg['num'],
                'uid'=>$order['user_id'],
                'order_id'=>$order['id']
            ]);
            Db::name('user')->where('id', $order['user_id'])->setInc('alg', $alg['num']);
            Db::name('order')->where('id', $order['id'])->update(['is_tui'=>1]);
            return json(['code'=>1,'message'=>'成功']);
        }
        if ($data['type']=='get_shi') {
            $id=$data['id'];
            $info=Db::name('area')->where('fid', $id)->select();
            if ($info) {
                return json([
                    'code'=>1,
                    'data'=>$info
                ]);
            } else {
                return json([
                    'code'=>0,
                    'data'=>$info
                ]);
            }
        }
        
        
        
        
        return 0;
    }
    public function add()
    {
        if (request()->isPost()) {
            $data=input('post.');
            //	dump($data);
            if (!$data['goods_id']) {
                $this->error('数据不正确');
            }
            
            $out_trade_no=md5('tai_'.mt_rand(10000, 99999).time());
            $goods=Db::name('goods')->find($data["goods_id"]);
            
            
            // dump($data);
            // die;
            
            //$user=Db::name('user')->find($data["user_id"]);
            
            if ($data["pay_time"]) {
                $time=strtotime($data["pay_time"]);
            } else {
                $time=time();
            }
            if ($data['xian']) {
                $sheng=Db::name('area')->where('id', $data['sheng'])->value('label');
                $shi=Db::name('area')->where('id', $data['shi'])->value('label');
                $xian=Db::name('area')->where('id', $data['xian'])->value('label');
                $sheng_html=$sheng.'-'.$shi.'-'.$xian;
            } else {
                $sheng_html='';
            }
            
            
            $info=[
                'out_trade_no'=>$out_trade_no,
                'goods_id'=>$goods['id'],
                'user_id'=>0,
                'goods_price'=>$goods['shop_price'],
                'order_num'=>$data['goods_num'],
                'payment'=>$data['payment'],
                'pay_status'=>1,
                'order_type'=>2,
                'order_status'=>1,
                'create_time'=>$time-60,
                'update_time'=>$time-60,
                'order_time'=>$time,
                'goods_price_zong'=>(float)$goods['shop_price']*(float)$data['goods_num'],
                'address'=>$data["shou_address"] ,
                'sheng_html'=>$sheng_html,
                'pay_price'=>(float)$goods['shop_price']*(float)$data['goods_num'],
                'phone'=>$data['shou_phone'],
                'shou_name'=>$data['shou_name'],
                'lei'=>$goods['lei'],
                'is_houtai'=>1,
                'is_ting100'=>1
            ];
            Db::name('order')->insert($info);
            $this->success('数据添加成功');
        }
        return $this->fetch('', [
             'sheng'=>Db::name('area')->where('fid', 0)->select()
         ]);
    }
    public function ren()
    {
        $user=new Usermodel();
        $key=input('key') ? input('key') : '';
        $this->assign('key', $key);
        
        $user=$user
            ->where('name|phone', 'like', '%'.$key.'%')
            ->paginate(10, false, ['query'=>request()->param()])->each(function ($item, $key) {
                $f=Db::name('user')->where('id', $item->fid)->find();
                $item->fname = $f['name'] ?: $f['phone'];
                $item->xia = Db::name('user')->where('fid', $item->id)->count('id');
                
                $item->alg_zong_d=Db::name('user_fen')->where('uid', $item->id)->sum('alg_dong');
                $item->alg_zong_j=Db::name('user_fen')->where('uid', $item->id)->sum('alg_jing');
                $z1=Db::name('otc_new')->where('uid', $item->id)->where('lei', 3)->where('type', 1)->sum('kou_num');
                $z2=Db::name('otc_new')->where('to_uid', $item->id)->where('lei', 3)->where('type', 3)->sum('kou_num');
                $z=$z1+$z2;
                $item->alg_mai=$z;
            });
        //dump(Db::getLastSql());
            
        $this->assign('user', $user);
        $count1=Db::name('user')->count();
        $this->assign('count1', $count1);
        
        
        return $this->fetch();
    }
    public function xuan()
    {
        $key=input('key') ? input('key') : '';
        $this->assign('key', $key);
        
        $goodsRes=Db::name('goods')->where('goods_name', 'like', '%'.$key.'%')->order('id DESC')->paginate(10, false, ['query'=>request()->param()])->each(function ($item, $key) {
            $item['cate_id'] = Db::name('goods_cate')->where('id', $item['cate_id'])->value('name') ?? '其他';
            return $item;
        });
        ;
        $this->assign(['goodsRes'=>$goodsRes]);
        
        $count1=Db::name('goods')->count();
        $this->assign('count1', $count1);
        return $this->fetch();
    }
    public function edit()
    {  
     	$order = new Ordermodel();   
    	if(request()->isPost()) {
            $data=input('post.');            
//			$validate = Loader::validate('Order');            
//			if(!$validate->check($data)){            
//				$this->error($validate->getError());
            //			}

            if (isset($data['pay_status']) and $data['pay_status']) {
                //分钱
                
                $order=Db::name('order')->find(input('id'));
                
                $fen=Db::name('order')->where('id', $order['id'])->where('pay_status', 0)->update([
                    'pay_status'=>1,
                    'pay_price'=>$order['goods_price_zong'],//支付的金额
                    'order_time'=>time(),
                  ]);
                
                
                if ($order['lei']==1 and $fen) {
                    $user=Db::name('user')->find($order['user_id']);
                    Db::name('user')->where('id', $order['user_id'])->update([
                        'dou'=>$user['dou']+$order['goods_price_zong'],
                        'al'=>$user['al']+$order['goods_price_zong']*2
                    ]);
                    $this->fen($order['user_id'], $data['buyer_pay_amount']);
                }
            }
        

            $res=$order->save($data, ['id' => input('id')]);
            $ding=$order->where('order_status', '0')->count();
            if ($res) {
                if ($ding!=0) {
                    echo '<script>parent.parent.document.getElementById("lizhili_ding").innerHTML="订',$ding,'"</script>';
                } else {
                    echo '<script>parent.parent.document.getElementById("lizhili_ding").innerHTML="订"</script>';
                }
            
                return $this->success('修改成功', url('order/index', ['st'=>1]));
            } else {
                $this->error('订单修改失败了');
            }
        }
        
        $id=input('id');
        
        $data= $order
                ->alias('o')
                ->join('user m', "o.user_id = m.id", 'LEFT')
                ->field('o.*,m.name,m.phone,m.nickName as username,m.phone as mphone,m.address')
                ->where('o.id', $id)
                ->find();
                

                
        $this->assign('data', $data); 
       return $this->fetch();
    }
    public function xiang()
    {
        $id=input('id');
       $order = new Ordermodel();   
        $data= $order
                    ->alias('o')
                    ->join('user m', "o.user_id = m.id", 'LEFT')
                    ->field('o.*,m.name,m.phone,m.nickName as username,m.phone as mphone,m.address')
                    ->where('o.id', $id)
                    ->find();
                    
    
                    
        $this->assign('data', $data);
		$num=0;
		$jia=0;
		$fen=Db::name('alg')->where('type',3)->where('order_id',$id)->order('id asc')->select();
		foreach($fen as &$v){
			$user=Db::name('user')->where('id',$v['uid'])->find();
			$v['name']=$user['name'] ?: $user['phone'];
			$jia=$v['alg_jia'];
			$num+=$v['num'];
		}
		$this->assign('fen', $fen);
        return $this->fetch('',[
			'jia'=>$jia,
			'num'=>$num
		]);
    }
    public function goods()
    { 
      	$id=input('id');
        $goods=Db::name('order_goods')
        ->where('order_id', $id)
        ->order('id desc')
        ->select();
        
        $this->assign('goods', $goods);
        //dump($goods);
        //die;
        $count1=db('order_goods')->where('order_id', $id)->count();
        $this->assign('count1', $count1);
        return $this->fetch();
    }
    protected function fen($uid=0, $money=0)
    {
        if ($uid or $money) {
            //找到所有上一级
            $arr=$this->shang($uid);
            $a=[];
            foreach ($arr as $k=>$v) {
                if ($k==0) {
                    $a[]=[
                        'id'=>$v,
                        'money'=>$money*0.12
                    ];
                } else {
                    $a[]=[
                        'id'=>$v,
                        'money'=>$money*0.12*(0.5**$k)
                    ];
                }
            }
            foreach ($a as $v) {
                Db::name('user')->where('id', $v['id'])->setInc('alg_zong', $v['money']);
            }
        }
    }
    protected function shang($uid=0)
    {
        $m=Db::name('user')->where('id', $uid)->value('fid');
        static $arr_li=[];
        if ($m) {
            $arr_li[]=$m;
            $this->shang($m);
        }
        return $arr_li;
    }
}
